package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.constant.NumConstant;
import com.example.constant.SecurityConstant;
import com.example.entity.SpuComment;
import com.example.exception.BaseException;
import com.example.mapper.SpuCommentMapper;
import com.example.service.SpuCommentService;
import com.example.util.TxOssUtil;
import com.example.vo.IdHolder;
import com.example.vo.Result;
import com.example.vo.admin.AdminCommentVo;
import com.example.vo.comment.PageResult;
import com.example.vo.comment.SpuCommentDash;
import com.example.vo.comment.SpuCommentReply;
import com.example.vo.comment.SpuCommentVo;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Description:
 * @Author: aimi
 * @Create: 2024-05-16
 **/
@Service
public class SpuCommentServiceImpl extends ServiceImpl<SpuCommentMapper,SpuComment> implements SpuCommentService {
    @Resource
    private SpuCommentMapper spuCommentMapper;
    @Resource
    private TxOssUtil txOssUtil;

   //获取商品评论列表
    @Override
    public List<SpuCommentVo> getSpuCommentList(Long spuId, Integer pageNo, Integer sortType,Integer type) {
        //获取vo列表
        String sortStr = "";
        if(sortType == 0){
            sortStr = "likes";
        }else if (sortType == 1){
            sortStr = "create_time";
        }else {
            sortStr = "likes";
        }
        Long begin = (pageNo - 1) * 10L;
        List<SpuCommentVo> voList = spuCommentMapper.selectSpuCommentList(spuId, begin,sortStr,type);
        voList.forEach(vo->{
            ArrayList<SpuCommentVo> replyList = new ArrayList<>();
            getReplyList(spuId,vo.getId(),replyList);
            SpuCommentReply commentReply = new SpuCommentReply();
            commentReply.setTotal(replyList.size());
            commentReply.setList(replyList);
            vo.setReply(commentReply);
            //System.out.println("vo = " + vo);
        });

        return voList;
    }

    public void getReplyList(Long spuId, Long commentId, List<SpuCommentVo> list){
        List<SpuCommentVo> replyList = spuCommentMapper.selectReplyList(spuId,commentId);
        if(replyList != null && !replyList.isEmpty()){
            list.addAll(replyList);
            //如果回复列表不为空，则继续寻找该评论的回复评论
            replyList.forEach(reply->{
                getReplyList(spuId,reply.getId(),list);
            });
        }
    }



    @Override
    public Long getCommentCount(Long spuId) {
        QueryWrapper<SpuComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("spu_id",spuId);
        return spuCommentMapper.selectCount(queryWrapper);
    }

    @Override
    public Result addComment(SpuComment spuComment) {
        if(!StringUtils.hasLength(spuComment.getContent())){
            return Result.error("评论内容不能为空");
        }
        //封装评论数据
        Integer skuId = spuComment.getSkuId();
        //根据skuId获取spuId，暂时忽略
        Long spuId = 1L;

        spuComment.setSpuId(spuId);
        Long userId = IdHolder.getUserId();
        spuComment.setLikes(0);
        spuComment.setUserId(userId);
        spuComment.setCreateTime(LocalDateTime.now());
        spuComment.setStatus(true);
        System.out.println("spuComment = " + spuComment);
        spuCommentMapper.insert(spuComment);
        return Result.ok();
    }

    //获取用户在该商品下的点赞评论列表
    @Override
    public List<Long> getLikeIds(@RequestParam Long spuId) {
        Long userId = IdHolder.getUserId();
        if(userId == null){
            return new ArrayList<>();
        }
        return spuCommentMapper.getLikeIds(userId,spuId);
    }

    @Override
    public void deleteComment(Integer id) {
        SpuComment spuComment = spuCommentMapper.selectById(id);
        Long userId = IdHolder.getUserId();
        if(spuComment == null){
            throw new BaseException("评论不存在");
        }else if(!Objects.equals(spuComment.getUserId(), userId)){
            throw new BaseException("你没有发过该评论");
        }
        spuCommentMapper.deleteById(id);
    }

    //点赞/取消点赞商品评论
    @Override
    public void likeOrCancelLike(Long commentId) {
        SpuComment comment = spuCommentMapper.selectById(commentId);
        if(comment == null){
            throw new BaseException("评论不存在");
        }
        Long userId = IdHolder.getUserId();
        //严格来说，这里应该存在线程问题，使用set likes = likes +/- 1比较好
        // 取消点赞
        if(isLike(userId,commentId)) {
            comment.setLikes(comment.getLikes()-1);
            spuCommentMapper.cancelLikeComment(userId,commentId);
        }else{
            comment.setLikes(comment.getLikes()+1);
            spuCommentMapper.likeComment(userId,commentId,comment.getSpuId());
        }
        spuCommentMapper.updateById(comment);
    }

    //判断当前用户是否为该评论点赞
    private boolean isLike(Long userId,Long commentId){
        int count = spuCommentMapper.getUserLikeCount(userId,commentId);
        return count == 1;
    }

    @Override
    public SpuCommentDash getSpuCommentDash(Long spuId) {
        SpuCommentDash dash = spuCommentMapper.getSpuCommentDash(spuId);
        //如果该商品没有评论信息
        if(dash == null){
            dash = new SpuCommentDash();
            dash.setTotal(0);
            dash.setGoodNum(0);
            dash.setMiddleNum(0);
            dash.setBadNum(0);
            dash.setAverageScore(0);
        }else{
            dash.setTotal(dash.getGoodNum()+dash.getMiddleNum()+dash.getBadNum());
            dash.setAverageScore(dash.getTotalScore()/dash.getTotal());
        }

        return dash;
    }

    @Override
    public String upload(MultipartFile file) {
        String url = "";
        if(file != null){
            url = txOssUtil.upload(file,"comment");
        }
        //System.out.println("url = " + url);
        return url;
    }

    @Override
    public PageResult<AdminCommentVo> getCommentPage(Integer pageNo, Integer pageSize, String keyword) {
        int begin = (pageNo-1)*pageSize;
        List<AdminCommentVo> commentVoList = spuCommentMapper.getAdminCommentList(begin,pageSize,keyword);
        Long total = spuCommentMapper.getAdminCommentCount(keyword);
        return new PageResult<>(total,commentVoList);
    }
}